﻿CREATE OR REPLACE FUNCTION USER_ACTIONS_INSERT_FUNC()
RETURNS TRIGGER AS $$
BEGIN
    IF    ( NEW.ACTION_DATE >= DATE '2010-11-01' AND NEW.ACTION_DATE < DATE '2010-12-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2010_11 VALUES (NEW.*);
    ELSIF ( NEW.ACTION_DATE >= DATE '2010-12-01' AND NEW.ACTION_DATE < DATE '2011-01-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2010_12 VALUES (NEW.*);
    ELSIF ( NEW.ACTION_DATE >= DATE '2011-01-01' AND NEW.ACTION_DATE < DATE '2011-02-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2011_01 VALUES (NEW.*);
    ELSIF ( NEW.ACTION_DATE >= DATE '2011-02-01' AND NEW.ACTION_DATE < DATE '2011-03-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2011_02 VALUES (NEW.*);
    ELSIF ( NEW.ACTION_DATE >= DATE '2011-03-01' AND NEW.ACTION_DATE < DATE '2011-04-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2011_03 VALUES (NEW.*);
    ELSIF ( NEW.ACTION_DATE >= DATE '2011-04-01' AND NEW.ACTION_DATE < DATE '2011-05-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2011_04 VALUES (NEW.*);
    ELSIF ( NEW.ACTION_DATE >= DATE '2011-05-01' AND NEW.ACTION_DATE < DATE '2011-06-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2011_05 VALUES (NEW.*);
    ELSIF ( NEW.ACTION_DATE >= DATE '2011-06-01' AND NEW.ACTION_DATE < DATE '2011-07-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2011_06 VALUES (NEW.*);
    ELSIF ( NEW.ACTION_DATE >= DATE '2011-07-01' AND NEW.ACTION_DATE < DATE '2011-08-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2011_07 VALUES (NEW.*);
    ELSIF ( NEW.ACTION_DATE >= DATE '2011-08-01' AND NEW.ACTION_DATE < DATE '2011-09-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2011_08 VALUES (NEW.*);
    ELSIF ( NEW.ACTION_DATE >= DATE '2011-09-01' AND NEW.ACTION_DATE < DATE '2011-10-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2011_09 VALUES (NEW.*);
    ELSIF ( NEW.ACTION_DATE >= DATE '2011-10-01' AND NEW.ACTION_DATE < DATE '2011-11-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2011_10 VALUES (NEW.*);
    ELSIF ( NEW.ACTION_DATE >= DATE '2011-11-01' AND NEW.ACTION_DATE < DATE '2011-12-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2011_11 VALUES (NEW.*);
    ELSIF ( NEW.ACTION_DATE >= DATE '2011-12-01' AND NEW.ACTION_DATE < DATE '2012-01-01' ) THEN
        INSERT INTO "USER_ACTIONS_PARTITION".USER_ACTIONS_2011_12 VALUES (NEW.*);
    ELSE
        RAISE EXCEPTION 'ACTION_DATE out of range.  Fix the USER_ACTIONS_INSERT_FUNC() function!';
    END IF;
    RETURN NULL;
END;
$$
LANGUAGE plpgsql;

CREATE TRIGGER INSERT_USER_ACTIONS_TRIGGER
    BEFORE INSERT ON USER_ACTIONS
    FOR EACH ROW EXECUTE PROCEDURE USER_ACTIONS_INSERT_FUNC();


